import {eventBus, deBounce} from "@/utils"
import defaultGif from '@/assets/default.gif'

let images = [];

function setImg(img){
    img.dom.src = defaultGif;
    const clientHeight = document.documentElement.clientHeight;
    const Rect = img.dom.getBoundingClientRect();
    let height = Rect.height;
    if(Rect.top > -height && Rect.top < clientHeight){
        const tempImg = new Image();
        tempImg.src = img.src;
        tempImg.onload = () => {
            img.dom.src = tempImg.src;
        }
        images = images.filter(i => i !== img);
    }
}
 
function setImage(){
    for (const img of images) {
        //看是否已经加载完成了
        setImg(img)
    }
}
function handleScroll(){
    setImage();
}

eventBus.$on('mainScroll', deBounce(handleScroll, 50));
export default {
    inserted(el, bindings){
        const img = {
            dom: el,
            src: bindings.value
        };
        images.push(img);
        setImg(img);
    },
    unbind(el){
        images = images.filter(img => img.dom !== el)
    }
}